package cn.edu.cug.cs.gtl.oi.ui;

import cn.edu.cug.cs.gtl.oi.render.Render;
import cn.edu.cug.cs.gtl.protos.Layer;
import cn.edu.cug.cs.gtl.protos.Map;
import cn.edu.cug.cs.gtl.protos.Project;
import com.openinventor.inventor.SoDB;
import com.openinventor.inventor.SoInput;
import com.openinventor.inventor.nodes.SoNode;
import com.openinventor.inventor.nodes.SoSeparator;

import javax.swing.*;
import java.io.*;

public class MainApp {
    Project project = null;
    Map currentMap = null;
    Layer currentLayer = null;
    protected MainWindow mainWindow = null;

    public MainApp() {
        mainWindow = new MainWindow(this);
    }

    public MainWindow getMainWindow() {
        return mainWindow;
    }


    public Project getProject() {
        return this.project;
    }

    public Map getCurrentMap() {
        return currentMap;
    }

    public void setCurrentMap(Map currentMap) {
        this.currentMap = currentMap;
    }

    public Layer getCurrentLayer() {
        return currentLayer;
    }

    public void setCurrentLayer(Layer currentLayer) {
        this.currentLayer = currentLayer;
    }

    public SoNode readSceneGraph(String fileName) throws IOException {
        if (fileName.endsWith("h3d")) {
            this.project = readH3DFile(fileName);
            this.currentMap = this.project.getMap(0);
            this.currentLayer = this.currentMap.getLayer(0);
            return Render.createProjectNode(this.project);
        } else {
            SoInput input = new SoInput();

            if (!input.openFile(fileName)) {
                System.err.println("Cannot open file " + fileName);
                return null;
            }

            SoSeparator node = SoDB.readAll(input);
            if (node == null) {
                System.err.println("Problem reading file");
                input.closeFile();
                return null;
            }

            input.closeFile();
            return node;
        }
    }

    public static Project readH3DFile(String fileName) throws IOException {
        if (fileName.endsWith("h3d")) {
            InputStream inputStream = new FileInputStream(new File(fileName));
            Project p = Project.parseFrom(inputStream);
            inputStream.close();
            return p;
        } else {
            throw new IOException("This file is not H3D file");
        }
    }

    public static void main(String[] args) {
        MainApp theApp = new MainApp();
        theApp.mainWindow.initial();
        theApp.mainWindow.setSize(1024, 768);
        theApp.mainWindow.pack();
        theApp.mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        theApp.mainWindow.setVisible(true);
    }
}
